<script setup>
import {onMounted, ref, reactive} from 'vue';
import {get, post} from '../js/http.js';
import connModal from '../components/modal/conn_modal.vue'
import icon from '../components/icon.vue'
import pageHead from '../components/pagehead.vue'
import nodata from '../components/nodata.vue'

const isEdit = ref(false)
let connData = ref([])
let currentConn= ref({})

onMounted(() => {
  getConn();
})

async function openModel(item, type) {
  isEdit.value = true
  currentConn.value = item
}
async function deleteHandle(item,itemIndex) {
  if(!item.id){
   return ;
  }
  post("/admin/conn/delete",item).then(res => {
    if (res.success) {
      window.message("保存成功", 'success')
      getConn();
      connData.value.splice(itemIndex,1);
    } else {
      window.message(res.message, 'warning')
    }
  }).catch(error => console.log(error))

}

function addHandle() {
  currentConn.value = {connName: "NewConnection",}
  isEdit.value = true
}

async function getPoolInfo() {

  get("/admin/conn/getPool").then(res => {
    //connData.value = res.result;
  })
  .catch(error => console.log(error))
}

async function getConn() {

  get("/admin/conn/get").then(res => {
    connData.value = res.result;
  })
  .catch(error => console.log(error))
}
async function closeModel() {
  isEdit.value = false

}
async function saveHandle() {
  isEdit.value = false
  let res = await post("/admin/conn/update", currentConn.value)
  if (res.success) {
    window.message("保存成功", 'success')
    getConn();
  } else {
    window.message(res.message, 'warning')
  }
}
</script>
<template>
  <pageHead title="数据源设置" iconName="shujuku">
    <button class="button is-link is-outlined mr-3" @click="getConn"><icon icon="refresh" class="is-link mr-1"></icon>刷新</button>
    <button class="button is-link is-outlined" @click="addHandle"><icon icon="add-bold" class="is-link mr-1"></icon>新增数据源</button>
  </pageHead>
  <div v-if="connData">
    <table class="table is-fullwidth">
      <thead>
      <tr>
        <th>数据源</th>
        <th>类型</th>
        <th>驱动</th>
        <th>用户名</th>
        <th>密码</th>
        <th style="text-align: center">操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item,itemIndex) in  connData" :key="item.Name">
        <td>{{ item.connName }}</td>
        <td :title="item.connUrl">{{ item.connType }}</td>
        <td>{{ item.connDriver}}</td>
        <td>{{ item.connUser }}</td>
        <td>{{ item.connPassword}}</td>
        <td style="text-align: center">
          <a @click="openModel(item,0)">设置</a>
          <a @click="deleteHandle(item,itemIndex)" class="ml-2">删除</a>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
  <nodata v-else></nodata>
  <connModal :currentConn="currentConn"   @close="closeModel" @save="saveHandle" v-if="isEdit==true"></connModal>

</template>
<style scoped>
</style>
